# 2025-20-09 完成级联菜单初始设计，初始化待测试
# 2025-3-16 完成streamChoice持久化设置（更正，上方为2025-2-14所制）
from PyQt5 import QtWidgets
import qdarkstyle
import sys

from appInfo import APP_VERSION
from ui.compiled.ui_settingsWindow import Ui_SettingsWindow
from util.config.ConfigManager import ConfigManager
from styleSheets import styleSheets


class LogicSettingsWindow(QtWidgets.QMainWindow):
    # 级联菜单字典
    models = {
        "DeepSeek": ["DeepSeek V3", "DeepSeek R1(Reasoning)"],
        "Xunfei": ["[Xunfei]DeepSeek V3", "[Xunfei]DeepSeek R1(Reasoning)"],
        "Alibaba": ["Qwen 2.5 Max(Reasoning)", "Qwen 2.5 Long"],
        "OpenAI": ["GPT 3.5 Turbo", "GPT 4"],
        "Google": ["Gemini 2 Flash", "Gemini 2 Pro"]
    }
    configManager = ConfigManager(
        org_name="JunhaxTech",
        app_name="JunhaxAI",
        app_version=APP_VERSION
    )
    def __init__(self, parent=None):
        super().__init__(parent)
        self.configManager.set("window/macos_style" if sys.platform == "darwin" else "window/default_style", True)
        self.ui = Ui_SettingsWindow()
        self.ui.setupUi(self)
        self.ui.settingsWidget.setCurrentIndex(0)
        # load_default_settings函数写好之后改掉
        self.load_default_settings()
        # self.ui.streamChoice.setCurrentIndex(0)  # 0->Enabled
        # self.ui.recoverChatChoice.setCurrentIndex(0)  # 0->Enabled
        self.ui.autoSaveChatChoice.setCurrentIndex(0)  # 0->Immediately
        self.ui.multiTurnChoice.setCurrentIndex(0)  # 0->Enabled
        self.ui.maxResponseEdit.setText("4096")  # Default max response tokens
        self.ui.tempEdit.setText("0.5")
        self.ui.apiPlatChoice.setCurrentIndex(1)
        self.ui.modelChoice.setCurrentIndex(2)
        self.ui.keyEdit.setText("Default API Key")

        self.monitor()


    # 绑定槽函数之函数
    def monitor(self):
        self.ui.themeChoice.currentIndexChanged.connect(self.change_theme)
        self.ui.historyManBtn.clicked.connect(self.test_connect)
        self.ui.apiPlatChoice.currentIndexChanged.connect(self.update_model_list)
        self.ui.streamChoice.currentIndexChanged.connect(self.update_stream_choice)
        self.ui.recoverChatChoice.currentIndexChanged.connect(self.update_recover_chat_choice)

    def load_default_settings(self):
        # 级联菜单
        self.ui.apiPlatChoice.addItems(self.models.keys())
        # 初始化Models
        # TODO:从文件读取
        self.ui.modelChoice.addItems(self.models["Xunfei"])
        print(">>>[INIT] Initialized model list(TODO)", self.models["Xunfei"])
        self.ui.modelChoice.setCurrentIndex(1)


        stream_choice_index=self.configManager.get("stream")
        # 如果为NoneType，则不曾配置过，设为0
        if stream_choice_index is None:
            stream_choice_index=0
        self.ui.streamChoice.setCurrentIndex(stream_choice_index)
        print(">>>[INIT] Initialized stream:",stream_choice_index)


        recover_chat_choice_index=self.configManager.get("recover_chat")
        if recover_chat_choice_index is None:
            recover_chat_choice_index=0
        self.ui.recoverChatChoice.setCurrentIndex(recover_chat_choice_index)
        print(">>>[INIT] Initialized recover chat:",recover_chat_choice_index)

    def update_stream_choice(self):
        self.configManager.set("stream", self.ui.streamChoice.currentIndex())
        # print("New stream Option:",self.ui.streamChoice.currentIndex())

    def update_recover_chat_choice(self):
        self.configManager.set("recover_chat", self.ui.recoverChatChoice.currentIndex())
    def update_model_list(self):
        print("READY TO UPDATE MODELS' LIST")
        self.ui.modelChoice.clear()
        # print("CurrentText",self.ui.apiPlatChoice.currentText())
        # print("List should be:",self.models[self.ui.apiPlatChoice.currentText()])
        self.ui.modelChoice.addItems(self.models[self.ui.apiPlatChoice.currentText()])

    def change_theme(self):
        print("RECEIVE SIGNAL")
        get_qss=styleSheets.styleSheets()
        new_theme = self.ui.themeChoice.currentText()
        if new_theme == "System":
            self.setStyleSheet("") # 清除样式
        elif new_theme == "Darcula":
            # set darcula style
            self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
        elif new_theme == "ElegantDark":
            self.setStyleSheet(get_qss.get_style(get_qss,"ElegantDark"))
        elif new_theme == "ManjaroMix":
            self.setStyleSheet(get_qss.get_style(get_qss,"ManjaroMix"))
        elif new_theme == "MaterialDark":
            self.setStyleSheet(get_qss.get_style(get_qss,"MaterialDark"))
        elif new_theme == "Ubuntu":
            self.setStyleSheet(get_qss.get_style(get_qss,"Ubuntu"))
        elif new_theme == "aqua":
            self.setStyleSheet(get_qss.get_style(get_qss,"aqua"))
        elif new_theme == "AMOLED":
            self.setStyleSheet(get_qss.get_style(get_qss,"AMOLED"))
        elif new_theme=="ConsoleStyle":
            self.setStyleSheet(get_qss.get_style(get_qss,"ConsoleStyle"))

    def test_connect(self):
        print("CONNECTED!")



# Hi! Here is a problem about slot binding
# Look Upon.